import { PropType } from "../Constant/Constant";
import PoolManager from "../Manager/PoolManager";

const { ccclass, property } = cc._decorator;

enum PropDirection {
  LEFT = 0,
  RIGHT = 1
}

/**
 * 道具控制类
 * 控制道具的移动和属性
 */
@ccclass
export default class PropControl extends cc.Component {
  @property
  speedY: number = 200

  @property
  speedX: number = 400

  public type: PropType = PropType.BLUE

  private direction: PropDirection = PropDirection.LEFT
  private leftBoundary = 0  // 左边边界
  private rightBoundary = 0 // 右边边界

  start() {
    this.leftBoundary = this.node.width * this.node.scale / 2 + 5  // 左边边界
    this.rightBoundary = cc.view.getVisibleSize().width - (this.node.width * this.node.scale / 2 - 5) // 右边边界
  }

  update(dt: number) {
    this.move(dt)
    // 道具跑出屏幕时销毁
    if (this.node.y < -this.node.height * this.node.scaleY) {
      PoolManager.instance.putNode(this.node)
    }
  }

  /**
   * 道具向下移动函数
   * @param dt 
   */
  private move(dt: number): void {
    // 向下移动
    this.node.y -= this.speedY * dt
    // 左右移动
    if (this.direction == PropDirection.LEFT) {
      this.node.x -= this.speedX * dt
      // 碰到边缘时更换方向
      if (this.node.x < this.leftBoundary) {
        this.direction = PropDirection.RIGHT
      }
    } else if (this.direction == PropDirection.RIGHT) {
      this.node.x += this.speedX * dt
      // 碰到边缘时更换方向
      // 右边边界
      if (this.node.x > this.rightBoundary) {
        this.direction = PropDirection.LEFT
      }
    }
  }

  /**
   * 当碰撞产生的时候调用
   * @param  {Collider} other 产生碰撞的另一个碰撞组件
   * @param  {Collider} self  产生碰撞的自身的碰撞组件
   */
  onCollisionEnter(other: cc.Collider, self: cc.Collider): void {
    console.log('on prop collision enter');
    PoolManager.instance.putNode(this.node)
  }
}
